#include "formdrugitems.h"
#include "ui_formdrugitems.h"
#include <QSettings>
#include "pub_var.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QFile>

FormDrugItems::FormDrugItems(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormDrugItems)
{
    ui->setupUi(this);

    QSettings setIni("clin.ini", QSettings::IniFormat);

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/drugitems").toRect();
    this->setGeometry(rct);

    //数据库连接

    qro = new QSqlQuery(pub::db_o);
    mdCurrent = new QSqlQueryModel();
    mdAll = new QSqlQueryModel();

    //默认界面状态
    ui->cbP->setChecked(true);
    ui->cbZ->setChecked(true);
    ui->rb1->setChecked(true);

    ui->tvAll->setFont(this->font());
    ui->tvCurrent->setFont(this->font());
    //
}

FormDrugItems::~FormDrugItems()
{
    delete ui;
}

void FormDrugItems::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/drugitems", QVariant(this->geometry()));
}

void FormDrugItems::on_pbSearch_clicked()
{
    QString range = ui->cbC->isChecked() ? "'C'" : "'0'";
    range.append(ui->cbP->isChecked() ? ",'P'" : ",'0'");
    range.append(ui->cbZ->isChecked() ? ",'Z'" : ",'0'");
    QString sq = " select distinct trade_name, specs, drug_code, spell_code, drug_type,"
                 " self_flag from ("
                 " select b.trade_name,b.specs,b.drug_code,b.spell_code,b.drug_type,"
                 " b.self_flag, s.store_sum "
                 " from pha_com_baseinfo b , pha_com_storage s"
                 " where  s.store_sum >0 and "
                 " b.drug_type in(" + range + ") and b.drug_code = s.drug_code "
                 " and b.valid_state = '1' and drug_dept_code = '" + pub::dp_code + "'"
                 " and b.spell_code like '" + ui->lePym->text().trimmed().toUpper() + "%' )";

    mdAll->setQuery(sq, pub::db_o);
    mdAll->setHeaderData(0, Qt::Horizontal, "品名");
    mdAll->setHeaderData(1, Qt::Horizontal, "规格");
    mdAll->setHeaderData(2, Qt::Horizontal, "药品码");
    ui->tvAll->setModel(mdAll);
    ui->tvAll->setColumnWidth(0, (ui->tvAll->width() -50 ) * 0.4);
    ui->tvAll->setColumnWidth(1, (ui->tvAll->width() -50 ) * 0.3);
    ui->tvAll->setColumnWidth(2, (ui->tvAll->width() -50 ) * 0.3);
    ui->tvAll->setColumnWidth(3, 0);
    ui->tvAll->setColumnWidth(4, 0);
    ui->tvAll->setColumnWidth(5, 0);
    ui->tvAll->setColumnWidth(6, 0);

    sq = "select drug_name, specs, drug_code, position, recal,package_num, valid,department, useage, come_from "
         " from drug_base_info where "
         "pym like '" + ui->lePym->text().trimmed().toUpper() + "%' "
         " order by position";

    mdCurrent->setQuery(sq, pub::db_o);
    mdCurrent->setHeaderData(0, Qt::Horizontal, "品名");
    mdCurrent->setHeaderData(1, Qt::Horizontal, "规格");
    mdCurrent->setHeaderData(2, Qt::Horizontal, "药品编码");
    mdCurrent->setHeaderData(3, Qt::Horizontal, "柜号");
    mdCurrent->setHeaderData(4, Qt::Horizontal, "校正数量");
    ui->tvCurrent->setModel(mdCurrent);
    ui->tvCurrent->setColumnWidth(0, (ui->tvCurrent->width() -50 ) * 0.30);
    ui->tvCurrent->setColumnWidth(1, (ui->tvCurrent->width() -50 ) * 0.20);
    ui->tvCurrent->setColumnWidth(2, (ui->tvCurrent->width() -50 ) * 0.20);
    ui->tvCurrent->setColumnWidth(3, (ui->tvCurrent->width() -50 ) * 0.15);
    ui->tvCurrent->setColumnWidth(4, (ui->tvCurrent->width() -50 ) * 0.15);
    ui->tvCurrent->setColumnWidth(5, 0);
    ui->tvCurrent->setColumnWidth(6, 0);
    ui->tvCurrent->setColumnWidth(7, 0);
    ui->tvCurrent->setColumnWidth(8, 0);
    ui->tvCurrent->setColumnWidth(9, 0);

    ui->leYpmc->clear();
    ui->leGg->clear();
    ui->leBm->clear();
    ui->leGh->clear();
    ui->leLsbc->clear();
    ui->leZjbzsl->clear();

}

void FormDrugItems::on_pbExit_clicked()
{
    close();
}

void FormDrugItems::on_tvAll_doubleClicked(const QModelIndex &index)
{
    QString str;
    str = index.siblingAtColumn(0).data(0).toString();
    ui->leYpmc->setText(str);
    str = index.siblingAtColumn(1).data(0).toString();
    ui->leGg->setText(str);
    str = index.siblingAtColumn(2).data(0).toString();
    ui->leBm->setText(str);

    spellCode = index.siblingAtColumn(3).data(0).toString();
    drugType = index.siblingAtColumn(4).data(0).toString();
    selfFlag = index.siblingAtColumn(5).data(0).toString();
}
void FormDrugItems::on_tvCurrent_doubleClicked(const QModelIndex &index)
{
    QString str;
    str = index.siblingAtColumn(0).data(0).toString().trimmed();
    ui->leYpmc->setText(str);
    str = index.siblingAtColumn(1).data(0).toString().trimmed();
    ui->leGg->setText(str);
    str = index.siblingAtColumn(2).data(0).toString().trimmed();
    ui->leBm->setText(str);
    str = index.siblingAtColumn(5).data(0).toString().trimmed();
    ui->leZjbzsl->setText(str);
    str = index.siblingAtColumn(3).data(0).toString().trimmed();
    ui->leGh->setText(str);
    str = index.siblingAtColumn(6).data(0).toString().trimmed();
    if(str == "0"){
        ui->rb0->setChecked(true);
    }else{
        ui->rb1->setChecked(true);
    }

    str = index.siblingAtColumn(4).data(0).toString().trimmed();
    ui->leLsbc->setText(str);
    str = index.siblingAtColumn(7).data(0).toString().trimmed();
    ui->cbbKs->setCurrentText(str.trimmed());
    str = index.siblingAtColumn(8).data(0).toString().trimmed();
    ui->cbbYf->setCurrentText(str.trimmed());
    ui->cbbLy->setCurrentText(index.siblingAtColumn(9).data(0).toString().trimmed());

     //0drug_name, 1specs, 2drug_code, 3position, 4recal,5package_num, 6valid,7department, 8usage

}
void FormDrugItems::on_pbSave_clicked()
{
    qro->exec("select drug_name from drug_base_info where drug_code = '"
              +ui->leBm->text()+ "'");
    qro->exec();
    if(qro->next()){    //已经有记录，修改
        qro->prepare("update drug_base_info set package_num = :package_num, position = :position,"
                     " valid = :valid, recal = :lsbc, department = :ks, useage = :yf, come_from = :come_from "
                     " where drug_code = :drug_code");
        qro->bindValue(":package_num", ui->leZjbzsl->text().toInt());
        qro->bindValue(":position", ui->leGh->text());
        qro->bindValue(":valid", (ui->rb0->isChecked()? "0" : "1"));
        qro->bindValue(":drug_code",ui->leBm->text());
        qro->bindValue(":lsbc",ui->leLsbc->text());
        qro->bindValue(":ks",ui->cbbKs->currentText());
        qro->bindValue(":yf",ui->cbbYf->currentText());
        qro->bindValue(":come_from",  ui->cbbLy->currentText() );
        if(qro->exec()){
            QMessageBox::information(this,"提示","记录修改成功！");
        }else{
            QMessageBox::information(this,"error", qro->lastError().text());
        }
    }else{              //无记录，新增
        qro->prepare("insert into drug_base_info (package_num,medicine_type,come_from,"
                     "drug_name,specs,position,drug_code,valid,recal,pym"
                     ")values("
                     ":package_num,:medicine_type,:come_from,"
                     ":drug_name,:specs,:position,:drug_code,:valid,0,:pym"
                     ") ");

        qro->bindValue(":drug_name",ui->leYpmc->text());
        qro->bindValue(":specs", ui->leGg->text());
        qro->bindValue(":drug_code",ui->leBm->text());
        qro->bindValue(":package_num", ui->leZjbzsl->text().toInt());
        qro->bindValue(":position", ui->leGh->text());
        qro->bindValue(":valid", (ui->rb0->isChecked()? "0" : "1"));
        qro->bindValue(":medicine_type", drugType );
        qro->bindValue(":pym", spellCode);
        qro->bindValue(":come_from", (selfFlag == "1" ? "制剂" : "外购"));
        if(qro->exec()){
            QMessageBox::information(this,"提示","记录保存成功！");
        }else{
            QMessageBox::information(this,"error", qro->lastError().text());
qDebug()<<qro->lastQuery();
        }

    }
    ui->leYpmc->clear();
    ui->leGg->clear();
    ui->leBm->clear();
    ui->leGh->clear();
    ui->leLsbc->clear();
    ui->leZjbzsl->clear();

}

void FormDrugItems::on_lePym_returnPressed()
{
    on_pbSearch_clicked();
}

void FormDrugItems::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    //窗口界面大小变化，重新设定
    ui->tvCurrent->setColumnWidth(0, (ui->tvCurrent->width() -50 ) * 0.40);
    ui->tvCurrent->setColumnWidth(1, (ui->tvCurrent->width() -50 ) * 0.30);
    ui->tvCurrent->setColumnWidth(2, (ui->tvCurrent->width() -50 ) * 0.30);
    ui->tvAll->setColumnWidth(0, (ui->tvAll->width() -50 ) * 0.4);
    ui->tvAll->setColumnWidth(1, (ui->tvAll->width() -50 ) * 0.3);
    ui->tvAll->setColumnWidth(2, (ui->tvAll->width() -50 ) * 0.3);
}
void FormDrugItems::on_pbLED_clicked()
{

    QString path = "d:/0down/led_" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".txt";

    //创建文件对象
    QFile file;
    //关联文件名字
    file.setFileName(path);
    //打开文件,只写方式
    bool isOK = file.open(QIODevice::WriteOnly);
    if (!isOK){
        QMessageBox::information(this,"注意","创建输出文件失败！");
        return;
    }

    QString sq = "select p.trade_name,d.name,p.specs,p.retail_price,f.fac_name, p.pack_unit "
                 " from pha_com_baseinfo p,PHA_COM_COMPANY f, com_dictionary d "
                 " where p.drug_code in(select drug_code from drug_base_info where valid = '1' ) "
                 " and f.fac_code = p.producer_code and d.sort_id = p.dose_model_code "
                 " and d.type = 'DOSAGEFORM'";
    qro->exec(sq);

    QString str ;
    while(qro->next()){
        str = qro->value(0).toString(); //品名
        str.append("  ");
        str.append(qro->value(1).toString());   //剂型
        str.append("  ");
        str.append(qro->value(2).toString() + "/" + qro->value(5).toString());  //规格、单位
        str.append("  ");
        str.append(QString::asprintf("%.2f",qro->value(3).toDouble()) + "元"); //价格
        str.append("  ");
        str.append(qro->value(4).toString());   //生产厂家
        str.append("  ");

        file.write(str.toLocal8Bit());
    }
    file.close();

    //write files
    //QString -> QByteArray
    // file.write(str.toUtf8());
    //QString -> C++ string ->char*
    //file.write(str.toStdString().data());
    QMessageBox::information(this,"注意", path+" 文件已生成！");
}
